package SGEngine2

import (
	"fmt"
	"github.com/gl"
	"image"
	"image/draw"
	_ "image/jpeg"
	_ "image/png"
	"os"
)

type Image struct {
	Texture *image.NRGBA
	TexID   gl.Texture
}

func LoadImage(path string) *Image {
	f, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	fimg, _, _ := image.Decode(f)
	NRGBAimg := image.NewNRGBA(fimg.Bounds())
	//	switch str {
	//	case "png":
	//		NRGBAimg, isNRGBA = fimg.(*image.NRGBA)
	//		if isNRGBA == false {
	//			draw.Draw(NRGBAimg, fimg.Bounds(), fimg, fimg.Bounds().Min, draw.Src)
	//		}
	//	case "jpeg":
	draw.Draw(NRGBAimg, fimg.Bounds(), fimg, fimg.Bounds().Min, draw.Src)
	//	}

	imgWidth, imgHeight := NRGBAimg.Bounds().Dx(), NRGBAimg.Bounds().Dy()
	data := make([]byte, imgWidth*imgHeight*4)
	lineLen := imgWidth * 4
	dest := len(data) - lineLen
	for src := 0; src < len(NRGBAimg.Pix); src += NRGBAimg.Stride {
		copy(data[dest:dest+lineLen], NRGBAimg.Pix[src:src+NRGBAimg.Stride])
		dest -= lineLen
	}

	TexId := gl.GenTexture()
	TexId.Bind(gl.TEXTURE_2D)
	gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
	gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
	gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
	gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
	gl.TexImage2D(gl.TEXTURE_2D, 0, 4, imgWidth, imgHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
	RT := &Image{NRGBAimg, TexId}
	return RT
}
